import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Select, TreeSelect, DatePicker, Checkbox, message, Dropdown, Menu, Icon, Modal } from 'antd'
import _ from 'lodash'
import moment from 'moment'

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import { getNewTreeData, findRowData, getNameByCode, confirmDelete, getYear, getNameByState, tableWidth, statistics, renderExt } from 'lib/fun'
import EditAuditor from './components/editAuditor'
import SubmitingUser from './components/submitingUser'
import FilterModule from './components/filterProjectJustUserRegisting'

const FormItem = Form.Item;
const SelectTreeNode = TreeSelect.TreeNode;
const { RangePicker } = DatePicker;
const Option = Select.Option;

class ModuleName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      data: [],
      projectList: [],
      visible: false,
      visible2: false,
      editType: "",
      rowdata: {},
      rowdata2: {},
      treeData: []
    }
    this.current = 1;   //当前第几页
    this.total = 0;   //总共多少页
    this.pageSize = 10;   //每页多少行
    this.search = {};
  }

  componentDidMount(){
    const { config, addConfig } = this.props;
    // load 项目列表
    this.loadProject();
    // citizen_info_type_code  人员分类没有找着
    this.loadData();
    if(!config.payObjCode){
      // 发放对象
      addConfig('payObjCode',10);
    }
    if(!config.payCycleCode){
      // 发放周期
      addConfig('payCycleCode',9);
    }
    if(this.props.common&&this.props.common.user&&this.props.common.user.user&&this.state.treeData.length == 0){
      this.loadArea(this.props.common.user.user.areaId);
    }
  }

  componentWillReceiveProps(nextProps){
    if(nextProps.common.user&&nextProps.common.user.user&&this.state.treeData.length == 0){
      this.loadArea(nextProps.common.user.user.areaId);
    }
  }


  loadArea = (areaId)=>{
    var self = this;
    if(self.loadAreaState){
      return
    }
    self.loadAreaState = true;
    Ajax({
      url: '/area/list',
      data: {
        areaParentId: areaId,
        perPage: 100
      },
      success: function(data){
        self.setState({
          treeData: data.list
        });
        self.loadAreaState = false;
      },
      error: function(error){
        message.error(error);
        self.loadAreaState = false;
      }
    });
  }

  pageOnChange = (page)=>{
    this.current = page;
    this.loadData();
  }

  showSizeChange = (current, pageSize)=>{
    var page = Math.ceil(((this.current-1)*this.pageSize+1)/pageSize);
    this.pageSize = pageSize;
    this.current = page;
    this.loadData();
  }

  loadProject = ()=>{
    var self = this;
    Ajax({
      url: '/project/list',
      data: {
        perPage: 10000,   //每页数量
      },
      success: function(data){
        self.setState({
          projectList: data.list
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  loadData = () => {
    var self = this;
    self.setState({
      loading: true
    });
    const {  } = this.search;
    Ajax({
      url: '/projectRegister/townsAuditoringList',
      data: Object.assign({}, this.search, {
        currentPage: self.current, 
        perPage: self.pageSize
      }),
      success: function(data){
        self.total = data.totalCount;
        self.setState({
          loading: false,
          data: data.list
        });
      },
      error: function(error){
        self.setState({
          loading: false
        });
        message.error(error);
      }
    });
  }

  handleFilter = (option)=>{
    if(!_.isEqual(option, this.search)){
      this.search = option;
      this.loadData();
    }
  }

  // 操作
  operate = (row)=>{
    this.setState({
      visible: true,
      rowdata: row
    });
  }
  
  renderContent = ()=>{
    return <Input id="reason" type="textarea"/>
  }

  // 提交上报
  approvalSubmit = (auditorType, batchId)=>{
    var self = this;
    var fun = (reason)=>{
      Ajax({
        url: '/projectRegister/townsAuditorSubmit',
        data: {
          batchId,
          auditorType,
          reason: reason?reason:undefined
        },
        success: function(data){
          if(auditorType == 1){
            var find = _.find(self.state.data, function(d) {
              return d.batchId == batchId
            });
            find.state = 30;
          }else{
            _.remove(self.state.data, function(d) {
              return d.batchId == batchId
            });
          }
          self.setState({
            data: self.state.data
          });
        },
        error: function(error){
          message.error(error);
        }
      });
    }
    if(auditorType==2){
      Modal.confirm({
        title: '确定打回请填写理由',
        content: self.renderContent(),
        onOk() {
          return new Promise((resolve, reject) => {
            var reason = document.getElementById('reason').value;
            fun(reason);
            resolve();
          }).catch(() => console.log('Oops errors!'));
        },
        onCancel() {},
      });
    }else{
      confirmDelete(()=>{
        fun();
      }, ()=>{
        message.info('取消操作');
      }, auditorType==3?'确认提交上报？':'确定要复核通过吗？');
    }
  }
  
  doDelete = (batchId)=>{
    var self = this;
    confirmDelete(()=>{
      Ajax({
        url: '/projectRegister/deleteRegisterBatch',
        data: {
          batchId
        },
        success: function(data){
          // _.remove(self.state.data, function(d) {
          //   return d.batchId == batchId
          // });
          // self.setState({
          //   data: self.state.data
          // });
          self.loadData();
        },
        error: function(error){
          message.error(error);
        }
      });
    }, ()=>{
      message.info('取消操作');
    }, '确定要删除吗？');
  }

  operate2 = (type, row, num)=>{
    if(num&&num>0){
      this.setState({
        visible2: true,
        editType: type,
        rowdata2: row
      });
    }
  }

  editOk = (b)=>{
    this.setState({
      visible:false
    })
    b&&this.loadData()
  }

  // 修改
  onEdit = (b)=>{
    this.setState({ 
      visible2: false 
    })
    b&&this.loadData();
  }

  render() {
    const { config, common } = this.props;
    const columns = [{
      title: '批次ID',
      dataIndex: 'batchId'
    }, {
      title: '项目编号',
      dataIndex: 'projectId'
    }, {
      title: '项目名称',
      dataIndex: 'projectName'
    }, {
      title: '补贴年度',
      dataIndex: 'year'
    }, {
      title: '发放周期',
      dataIndex: 'payCycleCode',
      render: (text, record) => (<span>{ getNameByCode(config, 'payCycleCode', text) }</span>)
    }, {
      title: '发放次数',
      dataIndex: 'subsidyCount'
    }, {
      title: '补贴登记区划',
      dataIndex: 'areaName'
    }, {
      title: '发放对象',
      dataIndex: 'payObjCode',
      render: (text, record) => (<span>{ getNameByCode(config, 'payObjCode', text) }</span>)
    }, {
      title: '总登记成功人数',
      dataIndex: 'totalCount',
      render: (text, record) => (<span><a href="javascript:;" title="查看详情" onClick={this.operate2.bind(this, 'total', record, text)}>{text?text:0}</a></span>)
    }, {
      title: '成功人数',
      dataIndex: 'successCount',
      render: (text, record) => (<span><a href="javascript:;" title="查看详情" onClick={this.operate2.bind(this, 'success', record, text)}>{text?text:0}</a></span>)
    }, {
      title: '成功金额',
      dataIndex: 'successMoney'
    }, {
      title: '失败人数',
      dataIndex: 'failCount',
      render: (text, record) => (<span><a href="javascript:;" title="查看详情" onClick={this.operate2.bind(this, 'fail', record, text)}>{text?text:0}</a></span>)
    }, {
      title: '失败原因',
      dataIndex: 'failReason'
    }, {
      title: '扩展属性',
      dataIndex: 'extStatList',
      render: (text, record) => (<span>{ renderExt(text) }</span>)
    }, {
      title: '状态',
      dataIndex: 'state',
      fixed: 'right',
      render: (text, record) => (<span>{ getNameByState(common, "projectRegisterBatchEn", text) }</span>)
    }, {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      render: (text, record) => <Dropdown overlay={
          record.state == 20?(
            <Menu>
              <Menu.Item>
                <a onClick={this.operate.bind(this, record)} href="javascript:;">复核人员</a>
              </Menu.Item>
              <Menu.Item>
                <a onClick={this.approvalSubmit.bind(this, 1, record.batchId)} href="javascript:;">批次复核通过</a>
              </Menu.Item>
              <Menu.Item>
                <a onClick={this.approvalSubmit.bind(this, 2, record.batchId)} href="javascript:;">打回</a>
              </Menu.Item>
              <Menu.Item>
                <a onClick={this.doDelete.bind(this, record.batchId)} href="javascript:;">删除</a>
              </Menu.Item>
            </Menu>
          ):(
            <Menu>
              <Menu.Item>
                <a onClick={this.approvalSubmit.bind(this, 3, record.batchId)} href="javascript:;">上报</a>
              </Menu.Item>
            </Menu>
          )
        
      }>
        <a className="ant-dropdown-link" href="javascript:;">
          操作 <Icon type="down" />
        </a>
      </Dropdown>
    }];

    var width = tableWidth(columns);

    var pagination = {
      current: this.current,
      total: this.total,
      pageSize: this.pageSize,
      onChange: this.pageOnChange,
      showSizeChanger: true,
      onShowSizeChange: this.showSizeChange,
      showTotal: total => `总共 ${total} 条`
    };

    return (
      <div className="area projectRegister">
        <FilterModule 
          handleFilter={ this.handleFilter }
          projectList={ this.state.projectList }
          treeData={this.state.treeData}
        />
        <div className="area-con">
          <Table 
            columns={columns}
            dataSource={this.state.data}
            pagination={pagination}
            rowKey="batchId"
            footer={ ()=> statistics(this.state.data) }
            scroll={{ x: width, y: false }}
            loading={ this.state.loading }
          />
        </div>
        <EditAuditor
          visible={ this.state.visible }
          batchId = { this.state.rowdata.batchId }
          onClose={ this.editOk }
          type="townsAuditorWaitCizList"
        />
        <SubmitingUser
          visible={this.state.visible2}
          onClose={this.onEdit}
          type={ this.state.editType }
          batchId = { this.state.rowdata2.batchId }
        />
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    config: state.config,
    common: state.common
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addConfig }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(ModuleName)